﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SMS.Account
{
    public partial class SearchUser : System.Web.UI.Page
    {
        SMS.Business.Users.UsersBusiness UB;
        SMS.Business.Roles.RolesBusiness RB;

        List<SMS.DAL.User> UsersFound
        {
            set
            {
                ViewState["UsersFound"] = value;
            }
            get
            {
                return (List<SMS.DAL.User>)(ViewState["UsersFound"]);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            UB = new Business.Users.UsersBusiness();
            RB = new Business.Roles.RolesBusiness();
            if (!IsPostBack)
            {
                drpRoles.DataSource = RB.Search(new DAL.Providers.RoleSearchCriteria());
                drpRoles.DataTextField = "Name";
                drpRoles.DataValueField = "ID";
                drpRoles.DataBind();
            }
        }

        protected void txtSearch_Click(object sender, EventArgs e)
        {
            UsersFound = UB.Search(new DAL.Providers.UserSearchCriteria() { RoleID = drpRoles.SelectedValue == "-1" ? (int?)null : int.Parse(drpRoles.SelectedValue), UserName = txtName.Text });
            GridView1.DataSource = UsersFound;
            this.DataBind();
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx?UserID=" + SMS.Helper.QueryEncoder.Encrypt(GridView1.SelectedDataKey.Value.ToString()));
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            UB.Delete((int)(e.Keys["ID"]));
            UsersFound.Remove(UsersFound.Where(t => t.ID == (int)(e.Keys["ID"])).SingleOrDefault());
            GridView1.DataSource = UsersFound;
            this.DataBind();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataSource = UsersFound;
            this.DataBind();
        }
    }
}